<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>销售分析图表</title>
  <th:block th:include="include :: header('销售分析图表')" />
  <style>
    .chart-container {
        width: 100%;
        height: 400px;
        margin-bottom: 30px;
        border: 1px solid #e7eaec;
        border-radius: 4px;
        padding: 15px;
        background: #fff;
    }
    .chart-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 18px;
        font-weight: bold;
    }
    .data-controls {
        margin-bottom: 20px;
        text-align: center;
    }
  </style>
</head>
<body class="gray-bg">
<div class="container-div">
  <div class="row">
    <div class="col-sm-12">
      <div class="ibox float-e-margins">
        <div class="ibox-title">
          <h5>销售数据分析</h5>
          <div class="ibox-tools">
            <a class="btn btn-primary btn-xs" th:href="@{/sale/item}">
              <i class="fa fa-arrow-left"></i> 返回列表
            </a>
          </div>
        </div>
        <div class="ibox-content">
          <!-- 数据控制面板 -->
          <div class="data-controls">
            <button id="refreshData" class="btn btn-info">
              <i class="fa fa-refresh"></i> 刷新模拟数据
            </button>
            <span class="help-block m-b-none">点击按钮生成新的随机模拟数据</span>
          </div>

          <!-- 热销产品柱状图 -->
          <div class="chart-container">
            <div class="chart-title">热销产品TOP10</div>
            <div id="barChart" style="width: 100%; height: 350px;"></div>
          </div>

          <!-- 销售趋势折线图 -->
          <div class="chart-container">
            <div class="chart-title">销售趋势分析</div>
            <div id="lineChart" style="width: 100%; height: 350px;"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<th:block th:include="include :: footer" />

<script th:inline="javascript">
  $(function() {
      // 初始化图表
      refreshCharts();

      // 绑定刷新按钮事件
      $('#refreshData').click(function() {
          refreshCharts();
      });
  });

  // 生成随机产品名称
  function generateProductNames(count) {
      var prefixes = ['智能', '超级', '便携', '无线', '多功能', '迷你', '专业', '家用', '商用', '高级'];
      var types = ['手机', '电脑', '平板', '电视', '耳机', '音箱', '手表', '相机', '打印机', '路由器'];
      var suffixes = ['Pro', 'Max', 'Plus', 'Lite', 'X', '2023', '旗舰版', '青春版'];

      var products = [];
      for (var i = 0; i < count; i++) {
          var name = '';
          // 随机组合名称
          if (Math.random() > 0.3) name += prefixes[Math.floor(Math.random() * prefixes.length)];
          name += types[Math.floor(Math.random() * types.length)];
          if (Math.random() > 0.5) name += suffixes[Math.floor(Math.random() * suffixes.length)];

          // 确保名称不重复
          if (products.indexOf(name) === -1) {
              products.push(name);
          } else {
              i--; // 重复则重新生成
          }
      }
      return products;
  }

  // 生成随机销售数据
  function generateSalesData(count, baseValue, variation) {
      var data = [];
      for (var i = 0; i < count; i++) {
          var value = baseValue * (1 - variation/2 + Math.random() * variation);
          data.push(Math.round(value));
      }
      return data;
  }

  // 生成趋势数据
  function generateTrendData(count, baseValue, growthRate) {
      var data = [baseValue];
      for (var i = 1; i < count; i++) {
          // 随机增长或下降
          var change = (Math.random() * 2 - 0.5) * growthRate;
          var newValue = data[i-1] * (1 + change/100);
          data.push(Math.round(newValue));
      }
      return data;
  }

  // 计算增长率
  function calculateGrowthRates(data) {
      var rates = [0];
      for (var i = 1; i < data.length; i++) {
          var rate = ((data[i] - data[i-1]) / data[i-1] * 100);
          rates.push(Math.round(rate * 10) / 10); // 保留一位小数
      }
      return rates;
  }

  // 刷新所有图表
  function refreshCharts() {
      // 重新生成模拟数据
      var productNames = generateProductNames(10);
      var salesAmounts = generateSalesData(10, 10000, 0.7); // 基础值10000，波动70%
      var salesQuantities = generateSalesData(10, 100, 0.6); // 基础值100，波动60%

      // 生成12个月的销售趋势
      var months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      var salesTrend = generateTrendData(12, 5000, 15); // 基础值5000，最大增长率15%
      var growthRate = calculateGrowthRates(salesTrend);

      // 更新柱状图
      initBarChart(productNames, salesAmounts, salesQuantities);

      // 更新折线图
      initLineChart(months, salesTrend, growthRate);

      toastr.success('模拟数据已刷新');
  }

  // 热销产品柱状图
  function initBarChart(productNames, salesAmounts, salesQuantities) {
      var barChart = echarts.init(document.getElementById('barChart'));

      var option = {
          tooltip: {
              trigger: 'axis',
              axisPointer: {
                  type: 'shadow'
              },
              formatter: function(params) {
                  var result = params[0].name + '<br/>';
                  params.forEach(function(item) {
                      result += item.marker + ' ' + item.seriesName + ': ' +
                                (item.seriesIndex === 0 ? '¥' + item.value : item.value) +
                                (item.seriesIndex === 1 ? '件' : '') + '<br/>';
                  });
                  return result;
              }
          },
          legend: {
              data: ['销售额', '销售数量']
          },
          grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis: {
              type: 'category',
              data: productNames,
              axisLabel: {
                  interval: 0,
                  rotate: 30
              }
          },
          yAxis: [
              {
                  type: 'value',
                  name: '销售额(元)',
                  axisLabel: {
                      formatter: '{value}'
                  }
              },
              {
                  type: 'value',
                  name: '销售数量',
                  axisLabel: {
                      formatter: '{value}'
                  }
              }
          ],
          series: [
              {
                  name: '销售额',
                  type: 'bar',
                  data: salesAmounts,
                  itemStyle: {
                      color: '#1ab394'
                  },
                  label: {
                      show: true,
                      position: 'top',
                      formatter: '¥{c}'
                  }
              },
              {
                  name: '销售数量',
                  type: 'bar',
                  yAxisIndex: 1,
                  data: salesQuantities,
                  itemStyle: {
                      color: '#23c6c8'
                  },
                  label: {
                      show: true,
                      position: 'top',
                      formatter: '{c}件'
                  }
              }
          ]
      };

      barChart.setOption(option, true);

      // 响应式调整
      window.addEventListener('resize', function() {
          barChart.resize();
      });
  }

  // 销售趋势折线图
  function initLineChart(months, salesTrend, growthRate) {
      var lineChart = echarts.init(document.getElementById('lineChart'));

      var option = {
          tooltip: {
              trigger: 'axis',
              axisPointer: {
                  type: 'cross',
                  label: {
                      backgroundColor: '#6a7985'
                  }
              },
              formatter: function(params) {
                  var result = params[0].name + '<br/>';
                  params.forEach(function(item) {
                      result += item.marker + ' ' + item.seriesName + ': ' +
                                (item.seriesIndex === 0 ? '¥' + item.value : item.value + '%') + '<br/>';
                  });
                  return result;
              }
          },
          legend: {
              data: ['销售额', '增长率']
          },
          grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis: {
              type: 'category',
              boundaryGap: false,
              data: months
          },
          yAxis: [
              {
                  type: 'value',
                  name: '销售额(元)',
                  axisLabel: {
                      formatter: '{value}'
                  }
              },
              {
                  type: 'value',
                  name: '增长率(%)',
                  axisLabel: {
                      formatter: '{value}%'
                  }
              }
          ],
          series: [
              {
                  name: '销售额',
                  type: 'line',
                  smooth: true,
                  data: salesTrend,
                  itemStyle: {
                      color: '#1c84c6'
                  },
                  areaStyle: {
                      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                          {
                              offset: 0,
                              color: 'rgba(28, 132, 198, 0.5)'
                          },
                          {
                              offset: 1,
                              color: 'rgba(28, 132, 198, 0.1)'
                          }
                      ])
                  },
                  label: {
                      show: true,
                      position: 'top',
                      formatter: '¥{c}'
                  }
              },
              {
                  name: '增长率',
                  type: 'line',
                  yAxisIndex: 1,
                  smooth: true,
                  data: growthRate,
                  itemStyle: {
                      color: '#f8ac59'
                  },
                  label: {
                      show: true,
                      position: 'top',
                      formatter: '{c}%'
                  }
              }
          ]
      };

      lineChart.setOption(option, true);

      // 响应式调整
      window.addEventListener('resize', function() {
          lineChart.resize();
      });
  }
</script>
</body>
</html>